<template>
  <div class="action-btn-wp">

    <el-button v-if="showBtn" type="primary" size="small" @click.stop.prevent="deliver()">发货</el-button>

    <el-dialog
        :visible.sync="dialogVisible"
        size="tiny"
        :close-on-click-modal="false"
        :before-close="handleClose">
      <span slot="title" style="font-weight: bold;font-size: 16px;">{{isEdit?'修改物流信息':'发货'}}</span>
      <div class="action-dialog-body">
        <el-form :model="form" :rules="rules" ref="form" label-width="6em">
          <el-form-item label="用户信息:">
            <div>
              <span>{{userInfo.name}}</span>
              <span> / {{userInfo.phone}}</span>
            </div>
            <div>{{userInfo.address}}</div>
          </el-form-item>
          <el-form-item label="物流公司:" prop="company">
            <el-select v-model="form.company" placeholder="请选择物流公司" style="width: 100%;">
              <el-option v-for="(item, index) in companyList " :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物流单号:" prop="number">
            <el-input v-model="form.number" placeholder="请输入物流／快递单号" style="width: 100%;"></el-input>
          </el-form-item>
          <el-form-item label="商品专属码" prop="sn">
            <el-input v-model="form.sn" placeholder="(此项选填)" style="width: 100%;"></el-input>
          </el-form-item>
          <el-form-item label="回寄地址:" prop="returnData">
            <contact-select @select-contact="handleSelect"></contact-select>
            <el-tooltip class="tooltip" effect="dark" :content="tip" placement="bottom">
              <i class="el-icon-information"></i>
            </el-tooltip>
          </el-form-item>
        </el-form>

      </div>
      <footer slot="footer" class="dialog-footer">
        <el-button @click="handleClose('form')">取 消</el-button>
        <el-button type="primary" @click="handelDeliver('form')" :loading="sending">确 定</el-button>
      </footer>
    </el-dialog>
  </div>
</template>

<script>
  import ContactSelect from '@/components/ContactSelect';
  import {orderDeliver, getOrderInfoBasic} from '@/api/order';
  import {serviceDeliver} from '@/api/afterService';
  import {showMessage} from '@/utils/message';

  export default {
    name: 'actionDeliver', //发货,修改发货信息
    components:{
      'contact-select':ContactSelect,
    },
    props: {
      showBtn:{
        type:Boolean,
        default:true,
      },
      isEdit:
      {
        type:Boolean,
        default:false,
      },
      scope: {
        type: Object,
        default: () => {
        },
      },
      scopeId: {
        type: String,
        default: 'id'
      },
      service:{ //售后维修换货的发货
        type:Boolean,
        default:false,
      },
    },
    data()
    {
      let validateReturn = (rule, value, callback) => {
        if (!value.returnName || !value.returnPhone || !value.returnAddress) {
          callback(new Error('请选择有效的回寄地址,或点击右边编辑图标添加'));
        } else {
          callback();
        }
      };

      let validateCompany = (rule, value, callback) => {
        console.log(value);
        if (!value) {
          callback(new Error('请选择物流公司'));
        } else {
          callback();
        }
      };

      return {
        dialogVisible: false,
        form: {
          company: '', //物流公司id
          number: '', //物流单号
          sn: '',// 商品sn码
          returnData: { //回寄信息,
            returnName:'', //回寄联系人
            returnPhone: '', //回寄联系电话
            returnAddress: '', //回寄地址
          },
        },
        rules:{
          company:[
            { required: true, validator:validateCompany, trigger: 'change' },
          ],
          number: [
            { required: true, message: '请输入物流/快递单号', trigger: 'change' },
          ],
          returnData:[
            { required: true, validator: validateReturn, type:'object',trigger: 'change' },
          ],
        },
        tip:'租赁到期后的寄回地址,可与寄件人地址不同',
        sending:false,
        userInfo:{ //发货用户地址
          name:'',
          phone:'',
          address:'',
        },
      }
    },
    computed:{
      companyList() //物流公司
      {
         return this.$store.getters.expresslist;
      },
      userAddress() //用户地址
      {
         return this.userInfo.name + ' / ' + this.userInfo.phone + ' / ' + this.userInfo.address;
      },
    },
    methods: {
      handleSelect(item)
      {
         this.form.returnData.returnName = item.name;
         this.form.returnData.returnPhone = item.phone;
         this.form.returnData.returnAddress= item.provice + item.city + item.regoin + item.text;
      },
      deliver() //点击发货按钮
      {
        //获取物流公司列表
        Promise.all([
          this.$store.dispatch('getExpressList'),
          this.$store.dispatch('getContactList',{data:{pageNum:1,pageSize:999}}),
        ]).then((resp)=>{
        });

        //获取回寄地址
        if(!this.service)
        {
          getOrderInfoBasic({id:this.scope.row['orderNumber']}).then(resp=>{
            let data = resp.data || {};
            this.userInfo = {
              name:data.contact || '',
              phone:data.contactPhone || data.userName || '用户未设置手机号',
              address:data.receiveAddress || '用户未设置收货地址',
            };

            this.dialogVisible = true;

          }).catch(err=>{

          });
        }else
        {
          let data = this.scope.row.userAddress || {};
          this.userInfo = {
            name:data.contactName || '等待用户设置联系人',
            phone:data.contactNumber || '等待用户设置手机号',
            address:data.address || '等待用户设置收货地址',
          };

          this.dialogVisible = true;
        }

      },
      handelDeliver(formName)
      {
        this.$refs[formName].validate((valid) => {
          if (valid) {

            if(!this.service) //正常发货
            {
              this.orderDeliver();
            }
            else //售后发货
            {
              this.serviceDeliver();
            }

          } else {
            return false;
          }
        });
      },
      orderDeliver() //正常发货
      {
        let id = this.scope.row.id;
        let channel = 'other';
        let data = {
          id:id,
          channel:channel,
          logisticsCompany:this.form.company,
          logisticsNumber:this.form.number,
          sn:this.form.sn,
          returnLinkman:this.form.returnData.returnName,
          returnLinkmanPhone:this.form.returnData.returnPhone,
          returnAddress:this.form.returnData.returnAddress,
        };

        this.sending = true;

        orderDeliver(channel,id,data).then(()=>{

          showMessage({title:this.isEdit?'已修改发货信息':'发货成功',type:'success'});
          this.dialogVisible=false;

          let rows = this.scope.rows;
          let index = this.scope.index;
          rows.splice(index,1);

          this.$emit('deliver-success');

          this.resetdata();

          this.sending = false;

        }).catch((err)=>{
          //console.log(err);
          this.sending = false;

        });
      },
      serviceDeliver() //售后维修换货发货
      {
        let id = this.scope.row.id;

        let data = {
          serviceOrderId:id,
          expressCompany:this.form.company,
          expressNo:this.form.number,
          contact:this.form.returnData.returnName,
          phone:this.form.returnData.returnPhone,
          receiveAddress:this.form.returnData.returnAddress,
          goodsSn:this.form.sn,
        };

        this.sending = true;

        serviceDeliver(data).then(()=>{

          showMessage({title:this.isEdit?'已修改发货信息':'发货成功',type:'success'});
          this.dialogVisible=false;

          let rows = this.scope.rows;
          let index = this.scope.index;
          rows.splice(index,1);

          this.$emit('deliver-success');

          this.resetdata();

          this.sending = false;

        }).catch((err)=>{
          //console.log(err);
          this.sending = false;

        });
      },
      resetdata()
      {
        this.$refs['form'].resetFields();
      },
      handleClose(done)
      {
        this.$confirm(this.isEdit?'确定暂不修改?':'确认暂不发货?')
          .then(_ => {
            this.dialogVisible=false;
            this.resetdata();
            done();
          })
          .catch(_ => {
          });

      },
    }
  }
</script>
<style lang="scss">
  .action-dialog-body
  {

    .el-form-item__content
    {
       position: relative;
       padding-right: 25px;

      .tooltip
      {
        position: absolute;
        top: 8px;
        right: 0;
        font-size: 20px;
      }
    }
  }

</style>